<!-- 新增编辑弹窗 -->
<template>
  <t-dialog
    :visible="visible"
    :width="680"
    :footer="false"
    :on-close="onClickClose"
    class="dialog-form"
  >
    <!-- 对话框头部 -->
    <template #header>
      <div class="dialog-header">
        <span class="dialog-title">{{ title }}</span>
        <span class="information">分类</span>
      </div>
    </template>
    <template #body>
      <!-- 表单内容 -->
      <t-table
        class="sort-table"
        row-key="id"
        :columns="columns"
        :show-header="false"
        :data="categoryList"
        drag-sort="row"
        @drag-sort="onDragSort"
      >
        <template #name="{ row }">
          <div>{{ row.name }}<t-icon name="move" class="move"></t-icon></div>
        </template>
      </t-table>
      <!-- end -->
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { saveProcessCategory } from "/src/api/process";
import { getFormCategoryList, saveFormCategory } from "@/api/form";
import { MessagePlugin } from "tdesign-vue-next";

const visible = ref(false)

const data = ref([])
const update = ref(false)
const onDragSort = (params) => {
  categoryList.value = params.newData
  const current = params.current
  const target = params.target
  if (current && target) {
    update.value = true
    const ord = target.ord
    target.ord = current.ord
    updateCategoryOrd(target)
    current.ord = ord
    updateCategoryOrd(current)
  }
}
// 触发父组件的方法
const emit: Function = defineEmits(['handleCloseSort'])

const categoryList = ref([])
// 关闭弹框
const onClickClose = () => {
  // 重置表单
  emit('handleCloseSort', update.value)
}

const updateCategoryOrd = async (row) => {
  const params = {
    id: 'FORM_CATEGORY_ADD_OR_UPDATE',
    palyload: {
      id: row.id,
      ord: row.ord
    }
  }
  await saveFormCategory(params)
}

const columns = [
  {
    colKey: 'name',
    title: '申请人',
    width: '100'
  }
]

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  list: {
    type: Array,
    default: []
  },
  data: {
    type: Object,
    default: () => {
      return {}
    }
  },
  appId: {
    type: String,
    default: () => {
      return ''
    }
  },
  title: {
    type: String,
    default: '新建产品'
  }
})
const fetchCategoryData = async () => {
  if (props.appId) {
    const params = {
      id: 'FORM_CATEGORY_LIST',
      palyload: {
        userAppId: props.appId
      }
    }
    const res: any = await getFormCategoryList(params)
    if (res.success) {
      categoryList.value = res.data.result.data
    } else {
      MessagePlugin.error(res.errorMessage)
    }
  }
}
watch(
  () => props.visible,
  () => {
    if (props.visible) {
      fetchCategoryData()
    }
    visible.value = props.visible
  }
)
</script>
<style lang="less">
.sort-table {
  border: 1px solid #e8e8e8;
  border-bottom: none;
}
.t-dialog__body {
  padding: 32px;
  max-height: 600px;
}
.move {
  float: right;
}
</style>
